package com.scut.campus.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.scut.campus.context.BaseContext;
import com.scut.campus.dto.PageDTO;
import com.scut.campus.dto.TradeDto;
import com.scut.campus.dto.TradeUpdateDto;
import com.scut.campus.entity.Trade;
import com.scut.campus.query.MainTradeQuery;
import com.scut.campus.query.TradeQuery;
import com.scut.campus.response.Result;
import com.scut.campus.service.TradeService;
import com.scut.campus.vo.TradeVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/trade")
@Tag(name = "交易功能")
@Slf4j
public class TradeController {
    @Autowired
    private TradeService tradeService;

    @PostMapping("/add")
    @Operation(summary = "新增商品")
    public Result insertLost(@RequestBody TradeDto tradeDto) throws IOException {
        Trade trade=new Trade();
        BeanUtils.copyProperties(tradeDto,trade);
        trade.setUserId(BaseContext.getCurrentId());

        //若有图片，进入匹配
        if(tradeDto.getPic1()!=null){
        }

/*
        TradeDoc tradeDoc = BeanUtil.copyProperties(trade,TradeDoc.class);
        String doc= JSONUtil.toJsonStr(tradeDoc);

        IndexRequest request=new IndexRequest("trades").id(tradeDoc.getTradeId().toString());
        request.source(doc, XContentType.JSON);

        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://8.138.180.23:9200")
        ));
        client.index(request, RequestOptions.DEFAULT);*/


        tradeService.save(trade);

        return Result.success();
    }

    @DeleteMapping("/delete/{tradeId}")
    @Operation(summary = "下架我的商品")
    public Result deleteByTradeId(@PathVariable("tradeId") Long tradeId){

        LambdaQueryWrapper<Trade>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Trade::getTradeId,tradeId)
                .eq(Trade::getUserId,BaseContext.getCurrentId());
        tradeService.remove(lambdaQueryWrapper);

        return Result.success();
    }

    @PostMapping("/queryMyTrade")
    @Operation(summary = "分页查询我的商品")
    public Result<PageDTO<Trade>> queryMyTrade(@RequestBody TradeQuery tradeQuery){
        PageDTO<Trade> tradePage=tradeService.queryMyTrade(tradeQuery);
        return Result.success(tradePage);

    }

    @PostMapping("/queryMainTrade")
    @Operation(summary = "查询主页展示商品")
    public Result<PageDTO<Trade>> queryMainTrade(@RequestBody MainTradeQuery mainTradeQuery) throws IOException {

        //若匹配词不为空，走elasticsearch
/*        if(mainTradeQuery.getMatch()!=null){
            SearchRequest searchRequest=new SearchRequest("trades");
            searchRequest.source()
                    .query(QueryBuilders.matchQuery("description",mainTradeQuery.getMatch()));
            searchRequest.source()
                    .from((int) ((mainTradeQuery.getPageNo()-1)*mainTradeQuery.getPageSize())).size(Math.toIntExact(mainTradeQuery.getPageSize()));

            RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                    HttpHost.create("http://8.138.180.23:9200")
            ));
            SearchResponse searchResponse=client.search(searchRequest,RequestOptions.DEFAULT);
            List<Long> mysqlSearchList=this.handleResponse(searchResponse);

            LambdaQueryWrapper<Trade>lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Trade::getTradeId,mysqlSearchList);

            PageDTO<Trade>tradePageDTO=new PageDTO<>((long) mysqlSearchList.size(),0L,tradeService.list(lambdaQueryWrapper));
            return Result.success(tradePageDTO);
        }*/


        PageDTO<Trade> tradePage= tradeService.queryMainTrade(mainTradeQuery);




        return Result.success(tradePage);

    }

    @GetMapping("/query/{tradeId}")
    @Operation(summary = "单独查询商品")
    public Result<TradeVo> querySingleTrade(@PathVariable("tradeId") Long tradeId) throws IOException {
        Trade trade=tradeService.getById(tradeId);
        TradeVo tradeVo =new TradeVo();
        BeanUtils.copyProperties(trade,tradeVo);
        tradeVo.setContactNo("2960911929");

/*        TradeDoc tradeDoc = BeanUtil.copyProperties(trade,TradeDoc.class);
        String doc= JSONUtil.toJsonStr(tradeDoc);

        IndexRequest request=new IndexRequest("trades").id(tradeDoc.getTradeId().toString());
        request.source(doc, XContentType.JSON);

        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://8.138.180.23:9200")
        ));
        client.index(request, RequestOptions.DEFAULT);*/
        return Result.success(tradeVo);
    }

    @PostMapping("/updateTrade")
    @Operation(summary = "修改商品")
    public Result updateTrade(@RequestBody TradeUpdateDto tradeUpdateDto){

        tradeService.updateTrade(tradeUpdateDto);
        return Result.success();

    }


/*    private List<Long> handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 2.遍历结果数组
        List<Long>elasticRes=new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化并打印
            TradeDoc tradeDoc = JSONUtil.toBean(source, TradeDoc.class);
            elasticRes.add(tradeDoc.getTradeId());
        }
        return elasticRes;
    }*/
}
